package com.aaa.util;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

public class FileUtil {

    /**
     * 图片上传
     *
     * @param file
     * @param path
     * @param request
     * @return 返回图片保存的路径
     */
    public static String upload(MultipartFile file,String path, HttpServletRequest request){
        String filename = file.getOriginalFilename();//原文件名
        String filePath = "D:\\AAA课程\\S3\\前后端分离项目1\\vue-manage-system-4.2.0\\src\\assets\\img\\";//文件真实路径
        String saveName = "";//新文件名 加上uuid
        if(null != filename && !"".equals(filename)){//非空判断
          //  filePath = request.getServletContext().getRealPath(path);//真实路径
            saveName = UUID.randomUUID().toString() + filename.substring(filename.lastIndexOf("."));//新文件名
            File saveFile = new File(filePath + saveName);//文件对象
            try {
                //System.out.println(saveFile);
                file.transferTo(saveFile);//另存方法
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return saveName;//返回
    }
    /**
     * 多文件
     * @param files
     * @param path
     * @param request
     * @return
     */
    public static String[] uploadFiles(MultipartFile[] files,String path, HttpServletRequest request){
        String[] paths = new String[files.length];///定一个字符串数组用来接受返回值
        for(int i=0;i<files.length;i++){
            paths[i] = upload(files[i], path, request);
        }
        return paths;
    }

}
